<script>
    $(function(){
        let callid='',
            nowPhone='',
            http_url=$('.http_url').val(),
            wsUrl=$('.wss_url').val()+'{$workerId}',
            ws='',
            callStatus='init',
            fromOtherPageNumber= sessionStorage.getItem('callNumber'),
            calljumpInfo= sessionStorage.getItem('calljumpInfo'),
            callOut_timer=null,
            callIn_timer=null;

        async function ajaxPromise(json) {
            return new Promise((resolve) => {
                $.ajax({
                    url: json.url,
                    method: json.method,
                    data: json.data,
                    success:function(res){
                        resolve(res);
                    }
                })
            });
        }
        
        {if $workerId}
            createWebSocket();
        {/if}
        $('body')
        //打开软电话软件
        .on('click','[data-fn="open-ztphone"]',function(){
            // location.href = 'ztphone://';
        })
        //轮播点呼出
        .on('click','[data-fn="callout"]',function(){
            let number=$(this).attr('data-telephone');
            callFunction(number);
        })
        // 下拉点呼出
        .on('click','[data-fn="hover-call"]',function(){
            let number=$(this).attr('data-telephone');
            $('.phone-dropdown').hide(); 
            callFunction(number);
        })
        //挂断
        .on('click','[data-fn="hangup"]',function(){
            hangupFunction($(this).attr('data-type'));
        })
        //呼入接听
        .on('click','[data-fn="answer"]',function(){
            answerFunction();
        })
        //呼入查询案件信息
        .on('click','[data-fn="callIn-searchBtn"]',function(){
            searchCasein($('[data-ele="callIn-seacth-input"]').val());
        })
        //接听面板跳详情页
        .on('click','[data-ele="jump-detal"]',function(){
            sessionStorage.setItem('calljumpInfo',JSON.stringify({
                phone: $(this).attr('data-telephone'),
                callInTimer: $('.callInTimer').html(),
                callid:  $(this).attr('data-callid'),
                status: callStatus,
            }));
            communicateCall({
                phone: $(this).attr('data-telephone'),
                callid:  $(this).attr('data-callid'),
                caseId: $(this).attr('data-caseId'),
            })
        })

        //心跳检测
        var heartCheck = {
            timeout: 30000, //每隔30秒发送心跳
            severTimeout: 20000,  //服务端超时时间
            timeoutObj: null,
            serverTimeoutObj: null,
            reset: function () {
                this.timeoutObj && clearTimeout(this.timeoutObj);
                this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
                return this;
            },
            start: function(){
                var self = this;
                this.timeoutObj && clearTimeout(this.timeoutObj);
                this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
                this.timeoutObj = setTimeout(function(){
                    //这里发送一个心跳，后端收到后，返回一个心跳消息，
                    ws.send('Hello')
                    self.serverTimeoutObj = setTimeout(function() {
                        ws.close();
                    }, self.severTimeout);

                }, this.timeout)
            }
        }

        async function createWebSocket(){
            if ('WebSocket' in window){
                ws = new WebSocket(wsUrl);
                window.ws=ws;
                ws.onopen = function () {
                    heartCheck.reset().start(); //心跳检测重置
                    if(fromOtherPageNumber){
                        callFunction(fromOtherPageNumber);
                        sessionStorage.removeItem('callNumber');
                    }
                };
                ws.onerror = function() {
                    createWebSocket();
                };
                socketPhoneStatus();
            }else{
                toastr.error('您的浏览器不支持WebSocket，无法使用电话业务');
            }
        }

        async function socketPhoneStatus(){
            ws.onmessage = async function (event) {
                try {
                    var res = JSON.parse(event.data)
                }catch(e) {
                    var res = event.data
                }
                console.log(res)
                let number= res.phone||'';
                //后端返回心跳在线
                if(res == 'Hi'){
                    heartCheck.reset().start();
                }//被迫下线
                else if(res.execute=='forced_0ffline'){
                    ws.close();  
                    $.confirm({
                        title: '注意！',
                        content: res.error||'出错啦！',
                        confirmButton: '确定',
                        cancelButton: '取消',
                        confirm: function(){
                        },
                        cancel: function(){
                        }
                    });
                }else if(res.result==400){
                    $('.user-name-word').html('<span data-fn="open-ztphone">请先注册软化机</span>');
                    $('[data-ele="busy-icon"]').show().siblings().hide();
                    // setTimeout(()=>{
                    //     ws.close();
                    //     createWebSocket();
                    // },2000)
                }else if(res.result&&res.result!=200){
                    $.confirm({
                        title: '注意！',
                        content: res.error||'出错啦！',
                        confirmButton: '确定',
                        cancelButton: '取消',
                        confirm: function(){
                        },
                        cancel: function(){
                        }
                    });
                }else if(res.result==200&&res.status==1){
                    $('.user-name-word').html($('.user-name-word').attr('data-num'));
                    $('[data-ele="normal-icon"]').show().siblings().hide();
                    $('[data-fn="callout"]').show();
                }else if(res.callType=='callOut_push'){
                        //呼出相关的
                        if(res.execute=='callOut_bell'){
                            callStatus='callOut_bell';
                            $('[name="callId"]').val(res.callId);
                            $('[name="type"]').val('1');
                            communicateCall({
                                phone: number,
                                callid: res.callId,
                                caseId: $('[name="caseId"]').val(),
                            })
                            $('[data-ele="phone-text-status"]').html(number.substring(0,3)+'****'+number.substring(number.length-4,number.length)+'接通中…').attr('data-phone',number);
                            $('[data-fn="hangup"]').show();
                            $('[data-hover="call"]').hide();
                        }else if(res.execute=='callOut_connect'){
                            callStatus='callOut_connect';
                            $('[name="callId"]').val(res.callId);
                            $('[name="type"]').val('1');
                            //呼出电话接通
                            $('[data-ele="phone-text-status"]').html(number.substring(0,3)+'****'+number.substring(number.length-4,number.length)+'已接通');
                            $('[data-fn="hangup"]').show();
                            $('[data-hover="call"]').hide();
                            clearInterval(callOut_timer);
                            clearInterval(callIn_timer);
                            callOut_timer = callOutTimer();
                        }else if(res.execute=='callOut_hangup'){
                            $('[name="callId"]').val(res.callId);
                            $('[name="type"]').val('1');
                            callStatus='callOut_hangup';
                            //呼出电话接通
                            $('[data-ele="phone-text-status"]').html(number.substring(0,3)+'****'+number.substring(number.length-4,number.length)+'已挂断');
                            $('[data-fn="hangup"]').hide();
                            $('[data-hover="call"]').show();
                            clearInterval(callOut_timer);
                            clearInterval(callIn_timer);
                        }
                    }else if(res.callType=='callIn_push'){
                        //呼入相关的
                        if(res.execute=='callIn_bell'){
                            //呼入响铃
                            callStatus='callIn_bell';
                            $('[name="type"]').val('2');
                            $('#callInModal').modal();
                            $('[data-ele="callIn-phone"]').html(number.substring(0,3)+'****'+number.substring(number.length-4,number.length)+'接通中…').attr('data-phone',number);
                            $('[data-ele="phone-text-status"]').html(number.substring(0,3)+'****'+number.substring(number.length-4,number.length)+'接通中…').attr('data-phone',number);
                            $('[data-fn="answer"]').show();
                            $('[data-fn="hangup"]').show();
                            callid= res.callId;
                            nowPhone = number;
                            await searchCasein(number);
                            $('[name="callId"]').val(res.callId);
                        }else if(res.execute=='callIn_connect'){
                            //呼入电话接通
                            callStatus='callIn_connect';
                            $('[name="type"]').val('2');
                            $('[data-ele="callIn-phone"]').html(number.substring(0,3)+'****'+number.substring(number.length-4,number.length)+'已接通');
                            $('[data-ele="phone-text-status"]').html(number.substring(0,3)+'****'+number.substring(number.length-4,number.length)+'已接通');
                            $('[data-fn="answer"]').hide();
                            $('[data-fn="hangup"]').show();
                            clearInterval(callIn_timer);
                            clearInterval(callOut_timer);
                            callIn_timer = callInTimer();
                            callOut_timer = callOutTimer();
                            $('[name="callId"]').val(res.callId);
                        }else if(res.execute=='callIn_hangup'){
                            //呼入电话接通
                            callStatus='callIn_hangup';
                            $('[name="type"]').val('2');
                            $('[data-ele="callIn-phone"]').html(number.substring(0,3)+'****'+number.substring(number.length-4,number.length)+'已挂断');
                            $('[data-ele="phone-text-status"]').html(number.substring(0,3)+'****'+number.substring(number.length-4,number.length)+'已挂断');
                            $('[data-fn="answer"]').hide();
                            $('[data-fn="hangup"]').hide();
                            $('[data-fn="hangup"]').hide();
                            $('[data-hover="call"]').show();
                            clearInterval(callIn_timer);
                            clearInterval(callOut_timer);
                            $('[name="callId"]').val(res.callId);
                        }
                    }
                // else{
                    //突然软件出问题
                    // ws && ws.close && ws.close();
                // }
            }
        }

        if(calljumpInfo){
            calljumpInfo=JSON.parse(calljumpInfo);
            sessionStorage.removeItem('calljumpInfo');
            clearInterval(callOut_timer);
            clearInterval(callIn_timer);
            $('[data-ele="phone-text-status"]').html(calljumpInfo.phone.substring(0,3)+'****'+calljumpInfo.phone.substring(calljumpInfo.phone.length-4,calljumpInfo.phone.length)+'呼入').attr('data-phone',calljumpInfo.phone);
            $('[data-fn="hangup"]').show();
            $('[data-hover="call"]').hide();
            $('[name="type"]').val('2');
            if(calljumpInfo.callInTimer){
                callOut_timer = callOutTimer(
                    calljumpInfo.callInTimer.substring(0,2),
                    calljumpInfo.callInTimer.substring(3,5),
                    calljumpInfo.callInTimer.substring(6,8),
                );
                setTimeout(function(){
                    if(calljumpInfo.status=='callIn_hangup'){
                        clearInterval(callOut_timer);
                        clearInterval(callIn_timer);
                        $('[data-fn="hangup"]').hide();
                        $('[data-hover="call"]').show();
                    }
                },1000)
            }
            $('[name="callId"]').val(calljumpInfo.callid);
        }

        function callOutTimer(h,m,s) {
            //秒
            var n_sec = s||0;
            //分
            var n_min = m||0;
            //时
            var n_hour = h||0;
            return setInterval(function () {
                n_sec++;
                if (n_sec > 59) {
                    n_sec = 0;
                    n_min++;
                }
                if (n_min > 59) {
                    n_sec = 0;
                    n_hour++;
                }
                var str_sec = n_sec;
                var str_min = n_min;
                var str_hour = n_hour;
                if (n_sec < 10) {
                    str_sec = "0" + n_sec;
                }
                if (n_min < 10) {
                    str_min = "0" + n_min;
                }
                if (n_hour < 10) {
                    str_hour = "0" + n_hour;
                }
                var time = str_hour + ":" + str_min + ":" + str_sec;
                $('.callOutTimer').html(time)
            }, 1000);
        }
        function callInTimer() {
            //秒
            var n_sec = 0;
            //分
            var n_min = 0;
            //时
            var n_hour = 0;
            return setInterval(function () {
                n_sec++;
                if (n_sec > 59) {
                    n_sec = 0;
                    n_min++;
                }
                if (n_min > 59) {
                    n_sec = 0;
                    n_hour++;
                }
                var str_sec = n_sec;
                var str_min = n_min;
                var str_hour = n_hour;
                if (n_sec < 10) {
                    str_sec = "0" + n_sec;
                }
                if (n_min < 10) {
                    str_min = "0" + n_min;
                }
                if (n_hour < 10) {
                    str_hour = "0" + n_hour;
                }
                var time = str_hour + ":" + str_min + ":" + str_sec;
                $('.callInTimer').html(time)
            }, 1000);
        }
        async function callFunction(number){
            {if !$workerId}
            toastr.error('暂无权限');
            return false;
            {/if}
            if(!ws){
                toastr.error('电话初始失败，请稍后再试');
                return false;
            }
            if(callStatus=='callOut_bell'||callStatus=='callOut_connect'||callStatus=='callIn_bell'||callStatus=='callIn_connect'){
                toastr.error('正在呼叫中，请稍后再试');
                return false;
            }
            callStatus='callOut_bell';
            ws.send(JSON.stringify({
                callType: 'callOut',
                execute: 'callOut',
                workerId: '{$workerId}',
                toTel: number,
                caseId: $('[name="caseId"]').val(),
            }))
        }
        async function answerFunction(){
            ws.send(JSON.stringify({
                callType: 'callIn_push',
            }))
        }
        async function hangupFunction(type){
            let number = $('[data-ele="phone-text-status"]').attr('data-phone')||$('[data-ele="callIn-phone"]').attr('data-phone');
            if($('[data-ele="callIn-phone"]').is(':visible')){
                //呼入电话接通
                $('[name="type"]').val('2');
                callStatus='callIn_hangup';
                $('[data-ele="callIn-phone"]').html(number.substring(0,3)+'****'+number.substring(number.length-4,number.length)+'已挂断');
                $('[data-ele="phone-text-status"]').html(number.substring(0,3)+'****'+number.substring(number.length-4,number.length)+'已挂断');
                $('[data-fn="answer"]').hide();
                $('[data-fn="hangup"]').hide();
                $('[data-fn="hangup"]').hide();
                $('[data-hover="call"]').show();
                clearInterval(callIn_timer);
                clearInterval(callOut_timer);
            }else{
                //呼出电话接通
                $('[name="type"]').val('1');
                callStatus='callOut_hangup';
                $('[data-ele="phone-text-status"]').html(number.substring(0,3)+'****'+number.substring(number.length-4,number.length)+'已挂断');
                $('[data-fn="hangup"]').hide();
                $('[data-hover="call"]').show();
                clearInterval(callOut_timer);
                clearInterval(callIn_timer);
            }
            ws.send(JSON.stringify({
                callType: type=='callOut'?'callOut':type=='callIn'?'callIn_hangup':'',
                execute: 'hangUp',
                workerId: '{$workerId}',
            }))
        }

        async function communicateCall(json){
            ajaxPromise({
                url: '/callinfo/call',
                method: "post",
                data: {
                    caseId: json.caseId,
                    phone: json.phone,
                    uuid: '',
                    callId: json.callid
                },
            })
        }
        async function searchCasein(search){
            let res= await ajaxPromise({
                url:"/callinfo/searchCasein",
                method: "post",
                data: {
                    search: search,
                },
            })
            if(res.code==200){
                if(res.data.length){
                    let hml='';
                    $.each(res.data,function(index,val){
                        hml+=`
                            <tr>
                                <td>${
                                    val.litigantName
                                }</td>
                                <td>${
                                    val.cardId
                                }</td>
                                <td>${
                                    val.mediateNum
                                }</td>
                                <td>
                                    <a href="/mediate/detail?caseId=${
                                        val.caseId
                                    }" 
                                    data-caseId="${
                                        val.caseId
                                    }"
                                    data-telephone="${
                                        nowPhone
                                    }"
                                    data-callid="${
                                        callid
                                    }"
                                    data-ele="jump-detal"
                                    >详情</a>
                                </td>
                            </tr>
                        `;
                    })
                    $('.case-tbody').html(hml);
                }else{
                    $('.case-tbody').html('未查询到数据');
                }
            }else{
                toastr.error(res.message);
            }
        }
    
    })

</script>